import { AxiosResult } from '@src/config/interface'
import axios from 'axios'
import { ElMessage } from 'element-plus'
const env = import.meta.env
const instance = axios.create({
  baseURL: env.VITE_BASE_PREFIX + env.VITE_BASE_VERSION,
  timeout: 60000,
})
// 请求拦截
instance.interceptors.request.use(
  function (config) {
    if (!config.headers['Content-Type']) {
      config.headers['Content-Type'] = 'application/json'
    }
    return config
  },
  function (error) {
    ElMessage.error('请求失败')
    return Promise.reject(error)
  },
)
// 响应拦截
instance.interceptors.response.use(
  function (response) {
    return response.data
  },
  function (error) {
    ElMessage.error(error.response.data.message)
    return Promise.reject(error)
  },
)
// post请求

export function APIPost(url: string, data: any, headers?: Record<string, string>): Promise<AxiosResult> {
  return new Promise((resolve, reject) => {
    instance({
      url: url,
      method: 'post',
      data: data,
      headers: {
        ...headers,
      },
    })
      .then((res: any) => {
        resolve(res)
      })
      .catch((err) => {
        reject(err)
      })
  })
}
// get请求
export function APIGet(url: string, params: any, headers?: Record<string, string>): Promise<AxiosResult> {
  return new Promise((resolve, reject) => {
    instance({
      url: url,
      method: 'get',
      params: params,
      headers: {
        ...headers,
      },
    })
      .then((res: any) => {
        resolve(res)
      })
      .catch((err) => {
        reject(err)
      })
  })
}
